﻿using System.Collections.Generic;
using DapperHelper.Enums;

namespace DapperHelper.SqlBuilder
{
    public class SqlBuilderFactory<T>
    {
        private SqlBuilderFactory()
        {
            SqlBuilders = new Dictionary<SqlType, ISqlBuilder<T>>();
        }

        private static SqlBuilderFactory<T> _factory;
        private static readonly object Locker;

        private IDictionary<SqlType, ISqlBuilder<T>> SqlBuilders { get; }

        public ISqlBuilder<T> GetSqlBuilder(SqlType type)
        {
            if (SqlBuilders.ContainsKey(type))
            {
                return SqlBuilders[type];
            }

            ISqlBuilder<T> builder;
            switch (type)
            {
                case SqlType.Insert:
                    builder = new InsertBuilder<T>();
                    break;
                default:
                    builder = null;
                    break;
            }

            if (builder != null)
            {
                SqlBuilders.Add(type, builder);
            }

            return SqlBuilders[type];
        }

        public static SqlBuilderFactory<T> BuilderFactory
        {
            get
            {
                if (_factory != null) return _factory;
                lock (Locker)
                {
                    _factory ??= new SqlBuilderFactory<T>();
                }

                return _factory;
            }   
        }
        
        static SqlBuilderFactory()
        {
            Locker = new object();
        }

        
    }
}